package com.chenwenxuan.sync.console;

import java.util.Hashtable;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.chenwenxuan.sync.Application;
import com.chenwenxuan.sync.Application.EventType;

public class MainThreadTaskExecutor extends ThreadPoolExecutor {

	private static final Logger innerlogger = Logger.getLogger(MainThreadTaskExecutor.class);
	
	public MainThreadTaskExecutor(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit,
			BlockingQueue<Runnable> workQueue) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new ThreadPoolExecutor.CallerRunsPolicy());
	}

	@Override
	public void shutdown() {
		super.shutdown();
		try {
			int i = 0;
			while (!awaitTermination(1, TimeUnit.SECONDS)) {
				if (i >= 10) {
					innerlogger.info("Waiting completion of threads.");
					i = 0;
				} else {
					i++;
				}

			}
		} catch (InterruptedException e) {
			return;
		}
	}

	@Override
	protected void afterExecute(Runnable r, Throwable t) {
		super.afterExecute(r, t);
		Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
		hashTable.put("source", this);
		hashTable.put("exception", t);
		hashTable.put("runnable", r);
		Application.getApplication().raiseEvent(EventType.TP_TASK_BEFORE_EXECUTE_EVENT, hashTable);
	}

	@Override
	protected void beforeExecute(Thread t, Runnable r) {
		Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
		hashTable.put("source", this);
		hashTable.put("thread", t);
		hashTable.put("runnable", r);
		Application.getApplication().raiseEvent(EventType.TP_TASK_BEFORE_EXECUTE_EVENT, hashTable);
		super.beforeExecute(t, r);
	}

}